package sample.cluster.factorial;

import akka.actor.UntypedActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;

import java.math.BigInteger;

//#backend
public class FactorialBackend extends UntypedActor {

  LoggingAdapter log = Logging.getLogger(getContext().system(), this);

  @Override
  public void onReceive(Object message) {
    if (message instanceof Integer) {
      final Integer n = (Integer) message;
//      Future<BigInteger> f = future(new Callable<BigInteger>() {
//        public BigInteger call() {
//          return factorial(n);
//        }
//      }, getContext().dispatcher());
//
//      Future<FactorialResult> result = f.map(
//          new Mapper<BigInteger, FactorialResult>() {
//            public FactorialResult apply(BigInteger factorial) {
//              return new FactorialResult(n, factorial);
//            }
//          }, getContext().dispatcher());

//      Future<FactorialResult> result = future(new Callable<FactorialResult>() {
//        public FactorialResult call() {
//          return new FactorialResult(n,factorial(n));
//        }
//      }, getContext().dispatcher());

      //
//      pipe(result, getContext().dispatcher()).to(getSender());
//      log.info("--------------------------"+n);
      BigInteger result = BigInteger.ONE;
      getSender().tell(result,getSelf());

    } else if(message instanceof MyMsg){
        log.info("******************************************"+((MyMsg) message).getDate().toString());
    } else {
      unhandled(message);
    }
  }

  BigInteger factorial(int n) {
    BigInteger acc = BigInteger.ONE;
    for (int i = 1; i <= n; ++i) {
      acc = acc.multiply(BigInteger.valueOf(i));
    }
    return acc;
  }


}
//#backend

